/*
 * 文 件    名:  SearchHistoryService.java
 * 创建日期:  2012-10-11上午11:17:19
 * 版          权:  Epro Technologies Co., Ltd. Copyright 2011-2012,  All rights reserved
 * 作          者:  cl073
 */
package com.weipu.common.facade.content.api;

import java.util.ArrayList;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.weipu.common.facade.content.BaseContentProvider;
import com.weipu.common.facade.content.BaseService;
import com.weipu.common.facade.content.ContentProviderFactory;
import com.weipu.common.facade.content.ContentURI;
import com.weipu.common.facade.content.colum.SearchHistoryColumn;
import com.weipu.common.facade.content.model.SearchHistoryModel;
import com.weipu.common.util.Logger;

/** 
 * @Description 模版管理service
 * @version [版本号, 2012-10-11]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 * 
 * @author cl073
 */
public class SearchHistoryService extends BaseService
{
    /**
      * 封装cursor为java bean
      * @param cursor
      * @return  [参数说明]
      * @return ArrayList<SearchHistoryModel> [返回类型说明]
      * @exception throws [违例类型] [违例说明]
      * @see [类、类#方法、类#成员]
      */
    private ArrayList<SearchHistoryModel> getListByCursor(Cursor cursor)
    {
        if (isNullOrEmpty(cursor))
        {
            close(cursor);
            return null;
        }
        ArrayList<SearchHistoryModel> modelList = new ArrayList<SearchHistoryModel>(cursor.getCount());
        int[] idx =
            {cursor.getColumnIndex(SearchHistoryColumn._ID),
                cursor.getColumnIndex(SearchHistoryColumn.SEARCHHISTORY_ID),
                cursor.getColumnIndex(SearchHistoryColumn.HISTORYNAME),
                cursor.getColumnIndex(SearchHistoryColumn.SEARCH_HISTORY_TIME)};
        do
        {
            SearchHistoryModel model = new SearchHistoryModel();
            if (-1 != idx[1])
            {
                model.setSearchHistoryId(cursor.getInt(idx[1]));
            }
            if (-1 != idx[2])
            {
                model.setName(cursor.getString(idx[2]));
            }
            if (-1 != idx[3])
            {
                model.setSearchTime(cursor.getLong(idx[3]));
            }
            modelList.add(model);
            
        } while (cursor.moveToNext());
        close(cursor);
        return modelList;
        
    }
    
    /**
      * 根据id查询
      * @param context
      * @param id
      * @return  [参数说明]
      * @return SearchHistoryModel [返回类型说明]
      * @exception throws [违例类型] [违例说明]
      * @see [类、类#方法、类#成员]
      */
    public SearchHistoryModel getById(Context context, long id)
    {
        if (!check(context))
        {
            return null;
        }
        if (id < 0)
        {
            return null;
        }
        ArrayList<SearchHistoryModel> modelList =
            getListByCursor(context.getContentResolver()
                .query(ContentUris.withAppendedId(ContentURI.ContentSearchHistory.CONTENT_URI_BY_ID, id),
                    null,
                    null,
                    null,
                    null));
        if (null == modelList || modelList.isEmpty())
        {
            return null;
        }
        return modelList.get(0);
    }
    
    /**
      * 自定义条件查询并返回游标
      * @param context
      * @param projection
      * @param selection
      * @param args
      * @param sortOrder
      * @return  [参数说明]
      * @return Cursor [返回类型说明]
      * @exception throws [违例类型] [违例说明]
      * @see [类、类#方法、类#成员]
      */
    public Cursor queryBySelection(Context context, String[] projection, String selection, String[] args,
        String sortOrder)
    {
        return context.getContentResolver().query(ContentURI.ContentSearchHistory.CONTENT_URI_ALL,
            projection,
            selection,
            args,
            sortOrder);
        
    }
    
    /**
     * 保存
     * @param context
     * @param model
     * @return [参数说明]
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public long save(Context context, SearchHistoryModel model)
    {
        if (!check(context, model))
        {
            return -1;
        }
        ContentValues map = model.template2map();
        try
        {
            context.getContentResolver().insert(ContentURI.ContentSearchHistory.CONTENT_URI_ALL, map);
        }
        catch (Exception e)
        {
            return -1;
        }
        return map.getAsLong(SearchHistoryColumn._ID);
    }
    
    /**
     * 更新
     * @param context
     * @param model
     * @return [参数说明]
     * @return long [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public long update(Context context, SearchHistoryModel model)
    {
        if (!check(context, model))
        {
            return -1;
        }
        
        if (model.getId() < 0)
        {
            return -1;
        }
        
        int updateRow = -1;
        try
        {
            updateRow =
                context.getContentResolver()
                    .update(ContentUris.withAppendedId(ContentURI.ContentSearchHistory.CONTENT_URI_BY_ID, model.getId()),
                        model.template2map(),
                        null,
                        null);
        }
        catch (Exception e)
        {
            //ignore
        }
        return updateRow;
    }
    
    /**
     * 自定义条件删除
     * @param context
     * @param selection 删除条件
     * @param args 条件参数
     * @return [参数说明]
     * @return int [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public int deleteTemplateBySelection(Context context, String selection, String[] args)
    {
        if (!check(context))
        {
            return -1;
        }
        
        int delete = -1;
        try
        {
            delete =
                context.getContentResolver().delete(ContentURI.ContentSearchHistory.CONTENT_URI_ALL, selection, args);
        }
        catch (Exception e)
        {
            //ignore
        }
        return delete;
    }
    
    public ArrayList<SearchHistoryModel> selectMenusList(Context context, String sortOrder)
    {
        Cursor cursor = this.queryBySelection(context, SearchHistoryColumn.RESULT, null, null, sortOrder);
        Logger.d("--cursor--", "--------" + cursor);
        
        ArrayList<SearchHistoryModel> menuList = new ArrayList<SearchHistoryModel>();
        if (cursor == null)
        {
            
        }
        else
        {
            
            cursor.moveToFirst();
            
            //数据集合不为空
            if (cursor.getCount() > 0)
            {
                do
                {
                    SearchHistoryModel temp = new SearchHistoryModel();
                    temp.setSearchHistoryId(cursor.getInt(1));
                    temp.setName(cursor.getString(2));
                    
                    menuList.add(temp);
                    
                    //后移
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return menuList;
    }
    
    /**
     * 删除搜索历史中第15数据之后的数据
     */
    public void deleteSearchHistoryNoUsedData(){
    	String deleteSql="delete from tbl_searchhistory where (select count(_id) from tbl_searchhistory)> 15 and _id in (select _id from tbl_searchhistory order by searchTime desc limit (select count(_id) from tbl_searchhistory) offset 15 )";
    	BaseContentProvider searchBCP=ContentProviderFactory.getContentProvier(ContentURI.ContentSearchHistory.CONTENT_URI_ALL);
    	if(null==searchBCP){
    		Log.i("SearchHistoryService", "searchBCP is null");
    		return;
    	}
    	searchBCP.deleteNoUsedData(deleteSql);
    }
    
}
